<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-row>
            <a-col :span="24" v-auth="'packaging:purchase'">
              <a-form-item label="工厂" v-bind="validateInfos.factory" >
                <j-search-select v-model:value="formData.factoryId"  dict="p_factory_manage,name,code"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24" v-auth="'packaging:purchase'">
              <a-form-item label="供应商" v-bind="validateInfos.packagingSupplierId" >
                <j-search-select v-model:value="formData.packagingSupplierId" :disabled="editVisit"  :dict="`p_packaging_supplier where factory_id='${formData.factoryId}',name,id`"  allow-clear />
              </a-form-item>
            </a-col>
						<a-col :span="24" v-auth="'packaging:factory'">
							<a-form-item label="供应商" v-bind="validateInfos.packagingSupplierId" >
								<j-search-select v-model:value="formData.packagingSupplierId"  :disabled="editVisit" :dict="`p_packaging_supplier where factory_id='${userInfo.factoryId}',name,id`"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="24">
              <a-form-item label="包材" v-bind="validateInfos.packagingId" v-auth="'packaging:purchase'">
                <j-select-input v-model:value="formData.packagingId" :disabled="editVisit" :async="true" :options="dictOptions"  allow-clear />
              </a-form-item>
              <a-form-item label="包材" v-bind="validateInfos.packagingId" v-auth="'packaging:factory'">
                <j-select-input v-model:value="formData.packagingId" :disabled="editVisit" :async="true" :options="dictOptions"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24" v-if="unitVisit">
              <a-form-item label="单位" v-bind="validateInfos.unit" >
                <j-search-select v-model:value="formData.unit" dict="unit_code"  allow-clear />
              </a-form-item>
            </a-col>
						<a-col :span="24">
							<a-form-item label="采购数" v-bind="validateInfos.arrivalNum">
								<a-input-number v-model:value="formData.arrivalNum" placeholder="请输入采购数"  :precision="2" :addon-after="unit" style="width: 100%" />
							</a-form-item>
						</a-col>
<!--						<a-col :span="24">-->
<!--							<a-form-item label="状态" v-bind="validateInfos.status">-->
<!--								<j-dict-select-tag v-model:value="formData.status" dictCode="supper_order_status" placeholder="请选择状态"  allow-clear />-->
<!--							</a-form-item>-->
<!--						</a-col>-->
						<a-col :span="24">
							<a-form-item label="备注" v-bind="validateInfos.remark">
								<a-input v-model:value="formData.remark" placeholder="请输入备注"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import {ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted, watch, unref} from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../PackagingOrder.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { useUserStore } from "/@/store/modules/user";
import {initDictOptions} from "@/utils/dict";
import JSelectInput from "@/components/Form/src/jeecg/components/JSelectInput.vue";
const userStore = useUserStore();
  const userInfo = userStore.getUserInfo;
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true }
  });
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
        id: '',
        factoryId: undefined,
        packagingSupplierId: '',   
        arrivalNum: undefined,
        status: undefined,
        remark: '',   
        packagingId: '',
        unit:'',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const unit = ref();
  const  dictOptions = ref ([]);
  const  unitVisit = ref<boolean>(false);
  const  editVisit = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    packagingSupplierId: [{ required: true, message: '请输入供应商id!'},],
    arrivalNum: [{ required: true, message: '请输入到货数!'},],
    packagingId: [{ required: true, message: '请输入包材id!'},],
    unit: []
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const formRef = ref();
  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

    const fetchDictOptions = async (factoryId) => { // 添加 async

        // 使用 await 等待异步操作完成
          try {
            // 使用 await 等待异步操作完成
            let url = '/packaging/packagingDetails/dict'
            if (factoryId) {
              url = '/packaging/packagingDetails/dict?factoryId='+factoryId
            }
            const res = await defHttp.get({ url: url });

            if (res && res.length > 0) {
              dictOptions.value = res.map((item) => ({
                label: item.name,
                value: item.id,
              }));
            } else {
              dictOptions.value = [];
            }
          } catch (e) {
            console.error('Error fetching packagingDetails dict:', e); // 添加错误日志
          }


    }

  watch(() => formData.packagingId, (newValue) => {
    console.log(newValue)
    if (newValue) {
      if (/[\u4e00-\u9fa5]/.test(newValue)) {
        unitVisit.value =true

        unit.value = ''
        validatorRules.unit = [{ required: true, message: '请输入单位!' }];
      }else {
        validatorRules.unit = [];
        unitVisit.value =false
        const dictData = initDictOptions('p_packaging_details,unit,unit,'+ encodeURIComponent(`id = '${newValue}'`))
        dictData.then(res=>{
          console.log(res[0])
          if (res[0]) {
            unit.value = res[0].value
          }else {
            unit.value = ''
          }

        })
      }
    }


  });

  watch(() => formData.factoryId, (newValue) => {
    console.log(newValue)
    if (newValue) {
      fetchDictOptions(newValue)
    }

  });

  
  /**
   * 新增
   */
  function add() {

    if (userInfo.factoryId) {
      fetchDictOptions(userInfo.factoryId)

    }
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    if (Object.keys(record).length === 0) {
      editVisit.value = false;
    } else {
      editVisit.value = true;
    }
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData,tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    if (unref(unit)) {
      model['unit'] = unref(unit);
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
    fetchDictOptions
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
